package com.leather.message.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leather.common.entity.Message;
import com.leather.common.entity.User;
import com.leather.common.result.CodeMsg;
import com.leather.common.result.Result;
import com.leather.common.toolkits.CheckKit;
import com.leather.common.vo.MessageVo;
import com.leather.message.feginclient.UserClient;
import com.leather.message.mapper.MessageMapper;
import com.leather.message.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private UserClient userClient;

    @Override
    public Result addMessage(MessageVo messageVo) {
        Result result = messageVo.validate();
        if (!result.isSuccess()) {
            return result;
        }
        //判断用户是否存在
        User user = userClient.getUserById(messageVo.getUserId());
        CheckKit.check(null != user, CodeMsg.ERROR_USER_ID);
        Message message = (Message) result.getData();
        CheckKit.check(save(message), CodeMsg.SERVER_ERROR);
        return Result.success(0);
    }

    @Override
    public Result getUserMessage(int userId, Page<Message> pages) {
        User user = userClient.getUserById(userId);
        CheckKit.check(null != user, CodeMsg.ERROR_USER_ID);
        List<Message> messages = query().eq("user_id", userId).orderByDesc("create_time").page(pages).getRecords();
        return Result.success(messages);
    }
}
